// index.js
// 获取应用实例
const app = getApp()
Page({
	data: {
		is_active: true,
		indicatorDots: true,
		vertical: false,
		autoplay: true,
		interval: 2000,
		duration: 500,
		advs:[],
		baseUrl:app.globalData.baseUrl,
		is_wxFinish:false,
		role:'',
	},
	onShow(){
		this.onInitLogin();
		this.setData({
			role:app.globalData.role
		})
		if(app.globalData.token){
			console.log(3)
			this.onGetUserInfo();
			this.onAdvert()
		}
	},
	onInitLogin(){
		var token = wx.getStorageSync('token');
		var time = wx.getStorageSync('time')?wx.getStorageSync('time'):0;
		if (new Date().getTime() - time > 3600 * 24 * 1000 * 7) {
			token = '';
			wx.clearStorage({
				success(res) {
					wx.redirectTo({
						url: '/pages/login/index',
					})
				}
			});
			return false
		}
		if(token){
			var records =  wx.getStorageSync('records')?JSON.parse(wx.getStorageSync('records')):'';
			app.globalData.token = token;
			app.globalData.records = records;
			app.globalData.time = time;
			console.log(2)
		}else{
			wx.redirectTo({
				url: '/pages/login/index',
			})
		} 
	},
	// 事件处理函数
	onLoad() {
		
		 
	},
	onAdvert(){
		let that = this;
		wx.request({
			url: app.globalData.baseUrl + '/api/index/advert',
			method: 'GET',
			header: {
				'content-type': 'application/x-www-form-urlencoded',
				'token': app.globalData.token,
			},
			success: function(res) {
				that.setData({
					advs:res.data.data.records
				})
				
				
			},
			fail: function() {
				console.log("请求失败")
			}
		})
	},
    onFinishWx(a,n,i,s){
		wx.login({
			success: (res) => {
			
				wx.request({
					url: app.globalData.baseUrl + '/api/index/finishWx',
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded',
						'token': app.globalData.token,
					},
					data:{
						'wx_avatar':a,
						'wx_nickname':n,
						'code':res.code
						// 'wx_union_id':u,
						// 'wx_samll_open_id':s
					},
					success: function(res) {
						
						
						
					},
					fail: function() {
					
						console.log("请求失败")
					}
				})
				
			},
			fail: (err) => {
				reject(err);
			}
		})
		
	},
	onGetWxInfo() {
		var that = this;
		if (app.globalData.userInfo) {
			return false;
		} else {
			wx.showModal({
				title: '提示',
				content: '是否授权获取用户信息？',
				success(res) {
					if (res.confirm) {
						that.getUserProfile()
					} else if (res.cancel) {
						console.log('用户点击取消')
					}
				}
			})
		}
	},
	onExit() {
		wx.clearStorage({
			success(res) {
				wx.redirectTo({
					url: '/pages/login/index',
				})
			}
		});
	},
	onGetUserInfo() {
		let that = this;
		wx.showLoading({
			title: '加载中',
			mask: true
		})
		wx.request({
			url: app.globalData.baseUrl + '/api/user/getUserInfo',
			method: 'GET',
			header: {
				'content-type': 'application/x-www-form-urlencoded',
				'token': app.globalData.token,
			},
			success: function(res) {
			
				if (res.data.status) {
					app.globalData.records = res.data.data.records;
					if(!app.globalData.role){
						app.globalData.role = res.data.data.records.type;
					}
					that.setData({
						role:app.globalData.role
					})
					if(app.globalData.role == 3){
						wx.redirectTo({
							url:'/pages/role/index'
						})
					}else {
						// that.onGetSeting();
						if(!res.data.data.records.is_finish_wx){
							that.onGetWxInfo()
						}
						
					}
				}
				wx.setStorage({
					key: "records",
					data: JSON.stringify(res.data.data.records)
				})
					
					wx.hideLoading()
			},
			fail: function() {
				wx.hideLoading()
				console.log("请求失败")
			}
		})
	},
	onGetSeting(){
		var _this = this;
		 wx.getSetting({
		      withSubscriptions: true, // 是否获取用户订阅消息的订阅状态，默认false不返回
		      success(res) {
		        console.log('res.authSetting', res.authSetting)
		        if (res.authSetting['scope.subscribeMessage']) {
		          console.log('用户点击了“总是保持以上，不再询问”')
		        } else {
		          console.log('用户没有点击“总是保持以上，不再询问”则每次都会调起订阅消息')
		          //因为没有选择总是保持，所以需要调起授权弹窗再次授权
		          _this.onGetSubscribe();
		        }
		      }
		})
	},
	
	onGetSubscribe(){
		let tmplIds = ['E1uJnAkLX8vwYngFDWyb3xxzGgV7KB5tWg_WT6lU7Hs']
		wx.requestSubscribeMessage({
		    tmplIds: tmplIds,
		    success: (res) => {
		        console.log("订阅消息 成功 " + res);
		    },
		    fail: (errCode, errMessage) => {
		        console.log( errCode , errMessage);
		    },
		    complete: (errMsg) => {
		        console.log("订阅消息 完成 " + errMsg); 
		    }
				
		});
	},
	sendWxinfo() {
		wx.showLoading({
			title: '加载中',
			mask: true
		})
		wx.request({
			url: app.globalData.baseUrl + '/api/my/getWxInfo',
			method: 'GET',
			header: {
				'content-type': 'application/x-www-form-urlencoded',
				'token': app.globalData.token,
			},
			data: {
				wx_info: app.globalData.userInfo
			},
			success: function(res) {
				wx.hideLoading()
				wx.setStorage({
					key: "openid",
					data: res.data
				})
				app.globalData.openId = res.data;
				app.globalData.is_finish_wx = true;
				// that.onLogin()
				// app.globalData.openId = 1;

				// that.saveUserInfo(app.globalData.openId);
			},
			fail: function() {
				wx.hideLoading()
				console.log("请求失败")
			}
		})
	},
	getUserProfile(e) {
		var that = this;
		// 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
		// 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
		if (wx.getUserProfile) {
			// wx.showLoading({
			// 	title: '加载中',
			// 	mask: true
			// })
			wx.getUserProfile({
				desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
				success: (res) => {
					wx.hideLoading();
					that.onFinishWx(res.userInfo.avatarUrl,res.userInfo.nickName)
				
					app.globalData.records.wx_avatar = res.userInfo.avatarUrl;
					app.globalData.records.wx_nickname = res.userInfo.nickName;

				}
			})
		} else {
			// 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
			wx.showModal({
				title: '提示',
				content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
			})
		}

	},

})
